<template>
	<a-drawer
		:title="formData.id ? '编辑' : '增加'"
		:width="500"
		:visible="visible"
		:destroy-on-close="true"
		:body-style="{ paddingBottom: '80px' }"
		:footer-style="{ textAlign: 'right' }"
		@close="onClose"
	>
		<a-tabs v-model:activeKey="activeKey">
			<a-tab-pane key="base" tab="销售单">
				<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
					<a-form-item label="销售门店：" name="storeCode">
						<a-select
							:disabled="readonly"
							v-model:value="formData.storeCode"
							:options="orgOptions"
							@change="onOrgChange"
							placeholder="请选择销售门店">
						</a-select>
					</a-form-item>
					<a-form-item label="支付方式：" name="payType">
						<a-select
							:disabled="readonly"
							v-model:value="formData.payType"
							:options="payTypeOptions"
							placeholder="请选择支付方式"></a-select>
					</a-form-item>
					<a-form-item label="支付金额：" name="payAmount">
						<a-input-number :disabled="readonly" v-model:value="formData.payAmount" style="width: 160px;" :min="0"/>
					</a-form-item>
					<a-form-item label="联系人：" name="buyerName">
						<a-input :disabled="readonly" v-model:value="formData.buyerName" :min="1" placeholder="请输入联系人姓名" allow-clear />
					</a-form-item>
					<a-form-item label="联系电话：" name="buyerPhone">
						<a-input :disabled="readonly" v-model:value="formData.buyerPhone" :min="1" placeholder="请输入联系电话" allow-clear />
					</a-form-item>
					<a-form-item label="备注：" name="note">
						<a-textarea :disabled="readonly" v-model:value="formData.note" placeholder="请输入备注" allow-clear />
					</a-form-item>
				</a-form>
			</a-tab-pane>
			<a-tab-pane :disabled="!searchFormState.storeCode" key="card" tab="录入方式">
				<a-tabs v-model:activeKey="inputKey" type="card">
					<a-tab-pane key="single" tab="单个录入">
						<s-table
							ref="table"
							:columns="columns"
							:data="loadData"
							:alert="options.alert.show"
							bordered
							:pagination="{ simple: true }"
							:row-key="(record) => record.id"
							:tool-config="toolConfig"
							:row-selection="options.rowSelection"
						>
							<template #operator class="table-operator">
								<a-select
									class="mb-4"
									style="width: 100%;"
									:disabled="readonly"
									v-model:value="searchFormState.cardType"
									:options="cardTypeOptions"
									placeholder="请选择卡类型"></a-select>
								<a-input-search
									class="mb-4"
									:disabled="readonly"
									v-model:value="searchFormState.code"
									placeholder="请输入卡号并回车搜索"
									enter-button="搜索"
									@search="table.refresh()"
								/>
								<a-row type="flex">
									<a-col :flex="1">
										<a-switch
											v-model:checked="autoActivate"
											un-checked-children="不激活"
											checked-children="立即激活"
										/>
									</a-col>
									<a-col>
										<div>已选择：{{ selectedRowKeys.length }}</div>
									</a-col>
								</a-row>

							</template>
						</s-table>
					</a-tab-pane>
					<a-tab-pane key="batch" tab="批量录入">
						<a-form ref="formRef2" :model="formData" label-align="right">
							<a-row>
								<a-select
									class="mb-4"
									style="width: 100%;"
									v-model:value="formData.cardType"
									:options="cardTypeOptions"
									placeholder="请选择卡类型"></a-select>
							</a-row>
							<a-form-item label="立即激活">
								<a-switch
									v-model:checked="autoActivate"
								/>
							</a-form-item>
							<a-form-item label="开始卡号">
								<a-input placeholder="请输入开始卡号" v-model:value="formData.startCode"/>
							</a-form-item>
							<a-form-item label="结束卡号">
								<a-input placeholder="请输入结束卡号" v-model:value="formData.endCode"/>
							</a-form-item>
						</a-form>
					</a-tab-pane>
				</a-tabs>
			</a-tab-pane>
		</a-tabs>
		<template #footer>
			<a-button style="margin-right: 8px" @click="onClose">关闭</a-button>
			<a-button type="primary" :loading="submitLoading" @click="onSubmit" :disabled="readonly">保存</a-button>
		</template>
		<Icon-selector ref="iconSelector" @iconCallBack="iconCallBack" />
	</a-drawer>
</template>

<script setup name="cardSaleForm">
	import { message } from 'ant-design-vue'
	import _ from 'lodash-es'
	import {required} from '@/utils/formRules'
	import IconSelector from '@/components/Selector/iconSelector.vue'
	import crmApi from '@/api/crm/crmApi'
	import { getCurrentInstance } from 'vue'
	import tool from "@/utils/tool";
	const searchFormState = reactive({
		status: 0,
		cardType: null,
		orderId: null,
		storeCode: null
	})
	// 默认是关闭状态
	let visible = $ref(false)
	let readonly = $ref(false)
	const emit = defineEmits({ successful: null })
	const formRef = ref()
	const formData = ref({})
	const submitLoading = ref(false)
	const iconSelector = ref()
	const activeKey = ref('base')
	const inputKey = ref('single')
	const autoActivate = ref(false)
	const table = ref(null)
	const toolConfig = {refresh: false, height: false, columnSetting: false, striped: false}
	const columns = [
		{
			title: '卡号',
			dataIndex: 'code'
		}
	]
	const { proxy } = getCurrentInstance()

	const loadData = (parameter) => {
		if (readonly) {
			return crmApi.cardSaleOrderItemPage({
				orderId: formData.value.id
			})
		} else {
			return crmApi.cardPage(Object.assign(parameter, searchFormState)).then((res) => {
				return res
			})
		}

	}

	const onOrgChange = (val) => {
		searchFormState.storeCode = val
	}

	// 打开抽屉
	const onOpen = (record, _readonly = false) => {
		visible = true
		readonly = _readonly
		formData.value = {
			payAmount: 0
		}
		searchFormState.cardType = cardTypeOptions[0].value
		if (record) {
			formData.value = Object.assign({}, record)
			searchFormState.storeCode = record.storeCode
		}
	}

	let selectedRowKeys = ref([])
	let selectedRows = ref([])
	// 列表选择配置
	const options = {
		alert: {
			show: false,
			clear: () => {
				selectedRowKeys = ref([])
				selectedRows = ref([])
			}
		},
		rowSelection: {
			onChange: (selectedRowKey, selectedRow) => {
				selectedRowKeys.value = selectedRowKey
				selectedRows.value = selectedRow
			}
		}
	}

	// 关闭抽屉
	const onClose = () => {
		formRef.value.resetFields()
		visible = false
		console.log(searchFormState)
		searchFormState.storeCode = undefined
		searchFormState.orderId = undefined
		searchFormState.status = 0
		activeKey.value = 'base'
		selectedRowKeys = ref([])
		selectedRows = ref([])
	}

	// 默认要校验的
	const formRules = {
		cardType: [required('请选择卡类型')],
		storeCode: [required('请选择销售门店')],
		payType: [required('请选择支付方式')],
		payAmount: [required('请输入支付金额')]
	}

	// 图标选择器回调
	const iconCallBack = (value) => {
		formData.value.icon = value
	}

	let payTypeOptions = proxy.$TOOL
		.dictTypeList('PAY_TYPE')
		.map((item) => {
			return {
				value: item['dictValue'],
				label: item['name']
			}
		})

	let cardTypeOptions = tool
		.tableList('CRM_CARD_TYPE')
		.map((item) => {
			return {
				prop: item['cardProp'],
				value: item['id'],
				label: item['name']
			}
		})

	let orgOptions = tool
		.tableList("ORG_CATEGORY")
		.map((item) => {
			return {
				value: item['code'],
				label: item['name']
			}
		})

	// 验证并提交数据
	const onSubmit = () => {
		formRef.value
			.validate()
			.then(() => {
				const param = Object.assign({}, formData.value)
				if (inputKey.value === 'batch') {
					if (!param.startCode || !param.endCode) {
						return message.error('开始卡号或者结束卡号不能为空')
					}
				}
				param.items = selectedRows.value.map(item => {
					return {
						cardId: item.id,
						cardNo: item.code,
						cardType: item.cardType,
						precharged: item.precharged
					}
				})
				param.autoActivate = autoActivate.value
				submitLoading.value = true
				crmApi.cardSaleOrderSubmitForm(param, param.id).then(() => {
					visible = false
					message.success('操作成功')
				}).finally(() => {
					submitLoading.value = false
				})
			})
	}

	// 调用这个函数将子组件的一些数据和方法暴露出去
	defineExpose({
		onOpen
	})
</script>
